Here is an example
to display date/time coming from the server.
//---- CLIENT:
window.addEventListener('load', function() { ... start_sse(); ... });
function start_sse()
{
if ('EventSource' in window) // Only when this browser supports SSE
{
var source = new EventSource("server_time.php?subject=COMP&no=3540"); // Can a URL include query?
// The browser usually reopens every 3 seconds.
// This can be controlled by the server using "retry:".
source.onopen = function(event) { ... }
source.onerror = function(event) { ... }
source.onmessage = function(event) {
// if (e.origin != '...') return; // for security concern
if (event.id == 'CLOSE') // user-defined id
source.close();
else // event.data
document.getElementById("server_time").innerHTML =
"The server time with 'message': " + event.data;
};
source.addEventListener('newevent', // a new user-defined event
// Can you use source.onnewevent = ...?
function(event) {
if (event.id == 'CLOSE')
source.close();
else // event.data
document.getElementById('server_time').innerHTML =
"The server time with 'newevent': " + event.data;
},);
}
else {
document.getElementById('message').innerHTML = 'No EventSource';
}
}
//---- SERVER: server_time.php
<?php
$subject = $_GET['subject'];
$number = $_GET['no'];
header("Content-Type: text/event-stream"); // This functions sends a raw HTTP header to a client.
header('Cache-Control: no-cache'); // You may refer to http://www.w3schools.com/php/func_http_header.asp
echo "retry: 3000\n"; // 3 seconds
// Use double quotes.
// If single quotes are used, \n will not be interpreted as the newline character, and
// this will make a trouble.
$count = 0;
while ($count < 3600) { // just one hour
if ($count++ % 2 == 0)
echo "event: newevent\n"; // use the new user-defined event 'newevent'
else
; // use the default event 'message'
$time = date('r');
echo "data: $time\n";
echo "\n"; // the end of a message
ob_flush(); // flush the output buffer
flush(); // flush the system buffer
sleep(1); // sleep 1 second
}
?>